//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package dao

import (
	"context"

	"gitcode.com/eteam/api-server/dao/common"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const (
	VERSION_KEY_SCHEMA  = "schema"
	VERSION_KEY_KEYWORD = "keyword"
)

type VersionDbItem struct {
	VersionKey string `bson:"_id"`
	Version    uint32 `bson:"version"`
}

type _VersionDao struct {
	mc *mongo.Collection
}

func newVersionDao(db *mongo.Database) (*_VersionDao, error) {
	mc := db.Collection(common.DB_NS_GLOBAL + "version")
	return &_VersionDao{mc: mc}, nil
}

func (db *_VersionDao) Exist(ctx context.Context, versionKey string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": versionKey})
	return count > 0, err
}

func (db *_VersionDao) Set(ctx context.Context, versionKey string, version uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": versionKey},
		bson.M{"$set": &VersionDbItem{
			VersionKey: versionKey,
			Version:    version,
		}}, options.Update().SetUpsert(true))
	return err
}

func (db *_VersionDao) Get(ctx context.Context, versionKey string) (*VersionDbItem, error) {
	retItem := &VersionDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": versionKey}).Decode(retItem)
	return retItem, err
}
